#coding=utf-8
#auth:beck shen
#date:2017-10-18


from pytw.core.tasklet import Tasklet

from twisted.internet import reactor


class Timer(object):

    """
    tasklet中运行reactor.callLater中的handler
    """

    def __init__(self, interval, handler, *args, **kwargs):
        self.inerval = interval
        self.handler = handler
        self.args = args
        self.kwargs = kwargs
        
        self._callid = reactor.callLater(interval, self._call)

    def _call(self):
        """
        运行于tasklet中
        """
        Tasklet.create(self.handler, *self.args, **self.kwargs)
    
    def cancel(self):
        try:
            self._callid.cancel()
        except:
            pass
        
